package com.tanhua.server.service;

import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.api.VoiceApi;
import com.tanhua.dubbo.pojo.Voice;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class VoiceMQService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @DubboReference(version = "1.0.0")
    private VoiceApi voiceApi;


    /**
     * 发布音频
     *
     * @return
     */
    public Boolean voiceMsg(String voiceId) {
        return this.sendMsg(voiceId, 1);
    }

    /**
     * 喜欢
     *
     * @return
     */
    public Boolean likeVoiceMsg(String voiceId) {
        return this.sendMsg(voiceId, 2);
    }

    /**
     * 不喜欢
     *
     * @return
     */
    public Boolean disLikeVoiceMsg(String voiceId) {
        return this.sendMsg(voiceId, 3);
    }




    /**
     * 发送音频操作相关的消息
     *
     * @param voiceId
     * @param type     1-发音频，2-喜欢， 3-不喜欢，
     * @return
     */
    private Boolean sendMsg(String voiceId, Integer type) {
        try {
            Voice voice = this.voiceApi.queryVoiceById(voiceId);
            //构建消息
            Map<String, Object> msg = new HashMap<>();
            msg.put("userId", UserThreadLocal.get());
            msg.put("date", System.currentTimeMillis());
            msg.put("voiceId", voiceId);
            msg.put("vid", voice.getVid());
            msg.put("type", type);

            this.rocketMQTemplate.convertAndSend("tanhua-voice", msg);
        } catch (Exception e) {
            log.error("发送消息失败! voiceId = " + voiceId + ", type = " + type, e);
            return false;
        }

        return true;
    }



}
